<template>
  <div class="app-container" style="display: flex;flex-direction: row;height: 100%;box-sizing: border-box">
    <el-card class="app-container"
             style="flex-grow: 1;flex-shrink: 1;flex-basis: 800px;overflow: auto;  padding-bottom:40px">
      <!--    试卷信息-->
      <div slot="header" style="text-align: center;position: relative">
        <h1 style="display: inline-block">{{ paperData.name }}</h1>
        <h3 style="display: inline-block;position: absolute; right: 100px;">答题人：{{
            paperData.userName
          }}</h3>
      </div>
      <!--    考题部分-->
      <div>
        <question @questionChange="handleQuestionChange" :state="paperData.state"
                  v-for="(item, index) in records" :data="item"
                  :prefix="index+1"
                  class="z-question"></question>
        <!--    操作按钮-->
        <div style="text-align: center;margin-top: 40px">
          <el-button
            v-if='~[options.TRAIN_TEST_PAPER_STATE.enums.WAIT_SUBMIT.value].indexOf(paperData.state)'
            @click="submit" type="primary" style="width: 500px">
            交卷
          </el-button>
          <el-button @click="closeTab" style="width: 150px">返回</el-button>
        </div>
      </div>
    </el-card>
    <!--    答题卡部分-->
    <div style="flex-basis: 300px;flex-grow: 0;flex-shrink: 0">
      <statistics :count="questionCount" :question-results="questionResultIndexMap"/>
    </div>
  </div>
</template>

<script>
import {submitPaper} from '@/api/train/base/Train.js'
import question from "./question";
import statistics from "./statistics";
import {QUESTION_TYPE, RESULT_TYPE, TRAIN_TEST_PAPER_STATE} from "@/views/train/Enums";
import {SEPARATOR} from "@/utils/Constant";
import {getPaperDetail, queryUserTrainPaper} from "@/api/train/base/Train";
import {mapGetters} from "vuex";
import mixins from "@/views/train/mixins";

export default {
  provide() {
    return {}
  },
  components: {question, statistics},
  mixins: [mixins],
  computed: {
    questionCount() {
      return this.records.length
    },
    ...mapGetters(['name']),
  },
  data() {
    return {
      // 试卷主体信息
      paperData: {},
      records: [],
      // 试卷ID
      paperId: '',
      questionResultMap: {},
      questionResultIndexMap: {},
      questionResultList: [],
      options: {
        QUESTION_TYPE: QUESTION_TYPE,
        RESULT_TYPE: RESULT_TYPE,
        TRAIN_TEST_PAPER_STATE: TRAIN_TEST_PAPER_STATE
      },
    }
  },
  methods: {
    // 提交试卷
    submit() {
      switch (this.paperData.state) {
        case this.options.TRAIN_TEST_PAPER_STATE.enums.WAIT_SUBMIT.value:
          this.submitAnswer()
          break
        default:
          this.$message.warning('当前试卷状态不允许提交')
      }
    },
    // 答完题后的提交试卷
    submitAnswer() {
      // 先找出所有未答完的题
      let unfinishedQuestions = []
      let paperAnswer = {
        paperId: this.paperId,
        answers: []
      }
      this.questionResultList.forEach(e => {
        let record = this.records.find(e1 => e.questionId === e1.questionId)
        let answer = {
          recordId: record.recordId,
          questionId: record.questionId,
          content: '',
          result: this.options.RESULT_TYPE.enums.ERROR.value,
          gainGrade: 0,
        }
        let gainGrade = 0
        // 如果是填空题,那么需要逐个选项判断,每个项的分数为总分/题目数量(四舍五入),如果全对,那么获得满分;如果不是全对,那么获得每个题的分数*做对的数量的分数
        if (this.options.QUESTION_TYPE.enums.FillBlankQuestionExcel.value === record.type) {
          let eachGrade = Math.round(record.grade / record.examQuestionBankOptionList.length)
          let keys = e.key.split(SEPARATOR)
          // 用于判断是否全对
          let isAllRight = keys.length === record.examQuestionBankOptionList.length
          keys.forEach((e, index) => {
            if (e === record.examQuestionBankOptionList[index].content) {
              gainGrade += eachGrade
            } else {
              isAllRight = false
            }
          })
          answer.content = e.key
          answer.gainGrade = isAllRight ? record.grade : gainGrade
          answer.result = isAllRight ? this.options.RESULT_TYPE.enums.RIGHT.value : this.options.RESULT_TYPE.enums.ERROR.value

          // 如果是判断题，那么严格校验
        } else if (record.type === this.options.QUESTION_TYPE.enums.JudgeQuestion.value) {

          answer.content = e.key
          if (e.key === record.rightKey) {
            answer.gainGrade = record.grade
            answer.result = this.options.RESULT_TYPE.enums.RIGHT.value
          } else {
            answer.result = this.options.RESULT_TYPE.enums.ERROR.value
          }
          // 如果是选择题，那么严格校验
        } else if (record.type === this.options.QUESTION_TYPE.enums.ChoiceQuestion.value) {
          let rightKeys = record.rightKey.split(',')
          // 多选题
          if (rightKeys.length > 1) {
            if(Array.isArray(e.key)){
              let isRight = true
              e.key.forEach(key => {
                if(!rightKeys.includes(key)){
                  isRight = false
                }
              })
              answer.content = e.key.toString()
              if(isRight){
                answer.result = this.options.RESULT_TYPE.enums.RIGHT.value
                answer.gainGrade = record.grade
              }else{

              }
            }else{
              // 错误的格式那么不处理就好(填空,0分)
            }
          } else {
            // 单选题
            answer.content = e.key
            if (e.key === record.rightKey) {
              answer.gainGrade = record.grade
              answer.result = this.options.RESULT_TYPE.enums.RIGHT.value
            } else {
            }
          }


          // 如果是论述题
        } else if (this.options.QUESTION_TYPE.enums.EssayQuestion.value === record.type) {
          answer.content = e.key
          // todo 论述题分数
        }
        if (!e.finished) {
          unfinishedQuestions.push(e.index)
        }
        paperAnswer.answers.push(answer)
      })
      unfinishedQuestions.sort((e1, e2) => e1 - e2)
      if (unfinishedQuestions.length) {
        this.$confirm(`您第${unfinishedQuestions.toString()}题尚未答完，确认交卷？`, '提示', {type: 'warning'}).then(
          () => {
            submitPaper(paperAnswer).then(res => {
              this.$message.success('交卷成功！')
              this.closeTab()
            })
          }
        )
      } else {
        this.$confirm(`试卷提交完后不可修改，确认交卷？`, '提示', {type: 'warning'}).then(
          () => {
            submitPaper(paperAnswer).then(res => {
              this.$message.success('交卷成功!')
              this.closeTab()
            })

          }
        )
      }
    },
    // 题目变动的事件
    handleQuestionChange({key, finished, questionId, index}) {
      this.questionResultMap[questionId] = {
        key, index, questionId, finished
      }
      this.$set(this.questionResultIndexMap, index, {
        key,
        index,
        questionId,
        finished,
      })
      let list = []
      Object.keys(this.questionResultMap).forEach(questionId => {
        list.push({
          ...this.questionResultMap[questionId]
        })
      })
      list.sort((e1, e2) =>
        e1.index - e2.index
      )
      this.questionResultList = list
    },
    closeTab() {
      this.$tab.closeOpenPage({path: '/train1/train'})
    }
  },
  mounted() {
    this.paperId = this.$route.params.paperId
    queryUserTrainPaper({id: this.paperId}).then(res => {
      this.paperData = res.rows[0]
      getPaperDetail(this.paperId).then(res => {
        this.records = res.data
      })
    })

  }
}
</script>
<style scoped>
.z-question + .z-question {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 15px #dcdfe6 solid;
}
</style>
